package com.stxx.stiot2.utils;

import cn.hutool.core.date.DateUtil;
import com.stxx.framwork.constants.ChangeType;
import com.stxx.framwork.utils.ObjectUtils;
import com.stxx.stiot2.domain.ext.SignalEx;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;

@Slf4j
public class SignalUtils {

    public static Boolean isTime(SignalEx signal, Long ts){
        if(signal.getNext()!=null&&signal.getNext()>ts){
            return false;
        }
        if(signal.getNext()==null){
            signal.setNext(ts+signal.getStoreInterval()*1000);
        }else{
            signal.setNext(signal.getNext()+signal.getStoreInterval()*1000);
        }
        return true;
    }


    public static Boolean isChange(Object oldValue, Object curValue,SignalEx signal){
        if(oldValue==null){
            return true;
        }
        if(ObjectUtils.equals(oldValue,curValue)){
            return false;
        }
        if(signal.getChangeType()== ChangeType.PRE){
            BigDecimal old = new BigDecimal(oldValue.toString());
            BigDecimal cur = new BigDecimal(curValue.toString());
            if(old.compareTo(BigDecimal.valueOf(0))!=0){
                if(old.subtract(cur)
                        .divide(old,5, RoundingMode.HALF_UP).multiply(BigDecimal.valueOf(100))
                        .abs().compareTo(BigDecimal.valueOf(signal.getChangeValue()))<0){
                    return false;
                }
            }
        }else if(signal.getChangeType()== ChangeType.ABC){
            BigDecimal old = new BigDecimal(oldValue.toString());
            BigDecimal cur = new BigDecimal(curValue.toString());
            if(old.subtract(cur).abs().compareTo(BigDecimal.valueOf(signal.getChangeValue()))<0){
                return false;
            }
        }
        return true;
    }
}
